Binary Tree Right Side View
Question
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
|
|
You should return [1, 3, 4].
Analysis
Version 1
- Each depth of the tree only select one node.
- View depth is current size of result list.
Version 2
- 层次遍历,在parent==0即要换层次的时候将当前节点的值加入res
Code
Version 1
|
|
Version 2
|
|
Populating Next Right Pointers in Each Node
Question
Follow up for problem “Populating Next Right Pointers in Each Node“.
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
|
|
After calling your function, the tree should look like:
|
|
Analysis
Version 1 见注释
Version 2 层次遍历,每次除了最后一个节点next=null,其余的next=当前队列最上层节点
Code
Version 1 (LeetCode Version)
|
|
Version 2
|
|